<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of GoogleSpreadsheet
 *
 * @author Namzul Hossain <nazmul.eps@gmail.com>
 */
include_once './classes/debug.php';

class GoogleSpreadsheet {

    private $client;
    private $spreadsheet;
    private $worksheet = "Sheet1";
    private $worksheet_id;

    public function __construct($user, $pass) {
        $this->login($user, $pass);
    }

    public function setSpreadsheetKey($sskey) {
        $this->spreadsheet = $sskey;
    }

    public function setWorksheet($ws) {
        $this->worksheet = $ws;
        $this->worksheet_id = NULL;
    }

    // http://code.google.com/apis/spreadsheets/docs/2.0/reference.html#ListParameters
    // user contribution by dmon (6/10/2009)
    public function getColumnNames() {
        $data = array();
        try {
            $query = new Zend_Gdata_Spreadsheets_ListQuery();
            $query->setSpreadsheetKey($this->getSpreadsheetKey());
            $query->setWorksheetId($this->getWorksheetId());
            $query->setMaxResults(1);
            $query->setStartIndex(1);
            $feed = $this->client->getListFeed($query);

            if ($feed->entries) {
                foreach ($feed->entries as $entry) {
                    if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
                        $customRow = $entry->getCustom();
                        foreach ($customRow as $customCol) {
                            array_push($data, $customCol->getColumnName());
                        }
                    }
                }
            }
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "getColumnNames");
        }
        return $data;
    }

    public function addRow($row) {
        try {
            if ($this->client instanceof Zend_Gdata_Spreadsheets) {
                $insert_row = array();
                foreach ($row as $k => $v)
                    $insert_row[$this->cleanKey($k)] = $v;

                $entry = $this->client->insertRow($insert_row, $this->getSpreadsheetKey(), $this->getWorksheetId());

                if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry)
                    return TRUE;
            }
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "addRow");
        }
        return FALSE;
    }

    public function getRows($search = FALSE) {
        $rows = array();
        try {
            if ($this->client instanceof Zend_Gdata_Spreadsheets) {
                $feed = $this->findRows($search);
                if ($feed->entries) {
                    foreach ($feed->entries as $entry) {
                        if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
                            $row = array();
                            $customRow = $entry->getCustom();
                            foreach ($customRow as $customCol) {
                                $row[$customCol->getColumnName()] = $customCol->getText();
                            }
                            $rows[] = $row;
                        }
                    }
                }
            }
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "getRows");
        }
        return $rows;
    }

    public function updateRow($row, $search) {
        try {
            if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search) {
                $feed = $this->findRows($search);
                if ($feed->entries) {
                    foreach ($feed->entries as $entry) {
                        if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
                            $update_row = array();
                            // overwrite with new values
                            foreach ($row as $k => $v) {
                                $update_row[$this->cleanKey($k)] = $v;
                            }
                            // update row data, then save
                            $entry = $this->client->updateRow($entry, $update_row);
                            if (!($entry instanceof Zend_Gdata_Spreadsheets_ListEntry))
                                return FALSE;
                        }
                    }
                    return TRUE;
                }
            }
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "updateRow");
        }
        return FALSE;
    }

    public function deleteRow($search) {
        try {
            if ($this->client instanceof Zend_Gdata_Spreadsheets AND $search) {
                $feed = $this->findRows($search);
                if ($feed->entries) {
                    foreach ($feed->entries as $entry) {
                        if ($entry instanceof Zend_Gdata_Spreadsheets_ListEntry) {
                            $this->client->deleteRow($entry);
                            if (!($entry instanceof Zend_Gdata_Spreadsheets_ListEntry))
                                return FALSE;
                        }
                    }
                    return TRUE;
                }
            }
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "deleteRow");
        }
        return FALSE;
    }

    private function login($user, $pass) {
        // Zend Gdata package required
        // http://framework.zend.com/download/gdata

        require_once 'Zend/Loader.php';
        Zend_Loader::loadClass('Zend_Http_Client');
        Zend_Loader::loadClass('Zend_Gdata');
        Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
        Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');

        $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
        $http = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
        $this->client = new Zend_Gdata_Spreadsheets($http);

        if ($this->client instanceof Zend_Gdata_Spreadsheets)
            return TRUE;

        return FALSE;
    }

    private function findRows($search = FALSE) {
        try {
            $query = new Zend_Gdata_Spreadsheets_ListQuery();
            $query->setSpreadsheetKey($this->getSpreadsheetKey());
            $query->setWorksheetId($this->getWorksheetId());
            wdebug($this->getSpreadsheetKey(), "SpreadsheetKey");
            wdebug($this->getWorksheetId(), "WorksheetId");
            if ($search)
                $query->setSpreadsheetQuery($search);

            $feed = $this->client->getListFeed($query);
        } catch (Zend_Gdata_App_Exception $exc) {
            wdebug($exc->getTraceAsString(), "findRows");
        }
        return $feed ? $feed : NULL;
    }

    private function getWorksheetId() {
        if ($this->worksheet_id)
            return $this->worksheet_id;

        if ($this->getWorksheet()) {
            $query = new Zend_Gdata_Spreadsheets_DocumentQuery();
            $query->setSpreadsheetKey($this->getSpreadsheetKey());
            $feed = $this->client->getWorksheetFeed($query);

            foreach ($feed->entries as $entry) {
                if ($entry->getTitle()->getText() == $this->getWorksheet()) {
                    $wk_id = array_pop(explode("/", $entry->id->text));
                    $this->worksheet_id = $wk_id;
                    break;
                }
            }
        }

        return $wk_id;
    }

    private function getWorksheet() {
        return $this->worksheet;
    }

    private function getSpreadsheetKey() {
        return $this->spreadsheet;
    }

    function cleanKey($k) {
        return strtolower(preg_replace('/[^A-Za-z0-9\-\.]+/', '', $k));
    }

    // currently not working
    private function getSpreadsheetId($ss = FALSE) {
        if ($this->spreadsheet_id)
            return $this->spreadsheet_id;

        $ss = $ss ? $ss : $this->spreadsheet;

        $ss_id = FALSE;

        $feed = $this->client->getSpreadsheetFeed();

        foreach ($feed->entries as $entry) {
            if ($entry->title->text == $ss) {
                $ss_id = array_pop(explode("/", $entry->id->text));

                $this->spreadsheet_id = $ss_id;

                break;
            }
        }

        return $ss_id;
    }

}
?>
